package com.example.myapplication;

import android.util.Log;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JsonObject {
    public JSONObject createJson() {
        JSONObject person=new JSONObject();
        JSONArray phone=new JSONArray();
        phone.add("12345");
        phone.add("67890");
        person.put("phone",phone);
        person.put("name","tang");
        JSONObject address=new JSONObject();
        address.put("street","Shanghai");
        address.put("city","Beijing");
        address.put("province","China");
        person.put("address",address);
        return person;
    }
    public JSONObject readJson(){
        InputStream inputStream = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;
        StringBuilder result=null;
        try {
            //得到资源中的Raw数据流
            inputStream = Files.newInputStream(Paths.get("res/raw/user.json"));
            reader = new InputStreamReader(inputStream);// 字符流
            bufferedReader = new BufferedReader(reader); //缓冲流
            result = new StringBuilder();
            String temp;
            while ((temp = bufferedReader.readLine()) != null) {
                result.append(temp);
            }
            Log.i("MainActivity", "result:" + result);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return JSONObject.parseObject(result.toString());
    }
}
